package server;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

public class StaticResourceUtil {

    // host --> 虚拟主机静态目录路径
    static HashMap<String, String> hostPathMap = new HashMap<>();

    // 默认虚拟主机
    static String defaultHost;

    static void initStaticConfig() {
        InputStream resourceAsStream = StaticResourceUtil.class.getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//Host");
            for (Element hostNode: selectNodes) {
                String name = hostNode.attribute("name").getStringValue();
                String appBase = hostNode.attribute("appBase").getStringValue();
                System.out.println(name);
                System.out.println(appBase);

                if (defaultHost == null) {
                    defaultHost = name;
                }

                hostPathMap.put(name, appBase);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取静态资源文件的绝对路径
     * @param
     * @return
     */
    public static String getAbsolutePath(Request request) {
        String path = request.getUrl();
//        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
//        absolutePath = java.net.URLDecoder.decode(absolutePath);

        String host = request.getHost();
        if (!hostPathMap.containsKey(host)) {
            host = defaultHost;
        }

        String absolutePath = hostPathMap.get(host);

        return absolutePath.replaceAll("\\\\","/") + path;
    }


    /**
     * 读取静态资源文件输入流，通过输出流输出
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {

        int count = 0;
        while(count == 0) {
            count = inputStream.available();
        }

        int resourceSize = count;
        // 输出http请求头,然后再输出具体内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        // 读取内容输出
        long written = 0 ;// 已经读取的内容长度
        int byteSize = 1024; // 计划每次缓冲的长度
        byte[] bytes = new byte[byteSize];

        while(written < resourceSize) {
            if(written  + byteSize > resourceSize) {  // 说明剩余未读取大小不足一个1024长度，那就按真实长度处理
                byteSize = (int) (resourceSize - written);  // 剩余的文件内容长度
                bytes = new byte[byteSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written+=byteSize;
        }
    }
}
